import React from 'react';
import { connect } from 'dva';
import { Tabs, Form, Steps, Popover, Table, Popconfirm, message, Input, Select, Row, Col, Checkbox, Button, Icon, Modal, Tag, Upload, Tree, Radio } from 'antd';
import cx from 'classnames'
import { isEmpty, cloneDeep, remove } from 'lodash'
import styles from './userInfoStyle.less'
import { Link, hashHistory } from 'dva/router'
import $ from 'jquery'
import Cookie from 'js-cookie'
import config from '../../../../config/config'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import ReactDOM from 'react-dom'
/*
 * 用户详情/新增/编辑
 * @author 廖玉宾
 * @time 未知
 * */
const Option = Select.Option;
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const Search = Input.Search;
const TreeNode = Tree.TreeNode;
const RadioGroup = Radio.Group;


const namespace = 'userInfoModel';
const routeObj = MODULE_TO_ROUTES[namespace];

const userInfoView = function ({ dispatch, userInfoModel, form }) {
	let {
		detail,
		type,
		checkedKeys,
		roleType,
		organizeList,
		roleTree,
		dutyList
	} = userInfoModel;

	const { getFieldDecorator, validateFields, setFieldsValue } = form;

	const formItemLayout = {
		labelCol: { span: 4 },
		wrapperCol: { span: 18 }
	};

	//状态值变化
	function updateModel(value, name, modHierarchy) {
		let obj = cloneDeep(userInfoModel);
		//trace记录每一个访问路径
		let trace = [];
		trace.push(obj);
		if (modHierarchy) {
			modHierarchy = modHierarchy.split(".");
			modHierarchy.forEach((item, index) => {
				trace.push(trace[index][item]);
			});
		}
		trace[trace.length - 1][name] = value;
		// 分发到model
		dispatch({
			type: `${namespace}/updateModel`,
			payload: obj
		});
	};

	function tree2list(tree) {
		const dataList = [];
		const generateList = (data) => {
			for (let i = 0; i < data.length; i++) {
				const node = data[i];
				const key = node.key;
				let obj = {
					key: node.key,
					id: String(node.id),
					name: node.name,
					parentId: node.parentId,
					children: node.children,
					applicationId: node.applicationId,
					status: node.status
				}
				dataList.push(obj);
				if (node.children && node.children.length > 0) {
					generateList(node.children, node.key);
				}
			}
		};
		generateList(tree);
		return dataList.slice(0);
	}

	const dataList = tree2list(roleTree);

	//可搜索树
	const getParentKey = (name, tree) => {
		let parentKey;
		for (let i = 0; i < tree.length; i++) {
			const node = tree[i];
			if (node.children) {
				if (node.children.some(item => item.name === name)) {
					parentKey = node.id + '';
				} else if (getParentKey(name, node.children)) {
					parentKey = getParentKey(name, node.children);
				}
			}
		}
		return parentKey;
	};

	const onExpand = (expandedKeys) => {
		dispatch({
			type: `${namespace}/updateModel`,
			payload: {
				expandedKeys,
				autoExpandParent: false,
			}
		});
	}

	const getSearchKey = (value) => {
		// const value = e.target.value;
		const expandedKeys = dataList.map((item) => {
			if (item.name.indexOf(value) > -1) {
				return getParentKey(item.name, roleTree);
			}
			return null;
		}).filter((item, i, self) => item && self.indexOf(item) === i);
		dispatch({
			type: `${namespace}/updateModel`,
			payload: {
				expandedKeys,
				searchValue: value,
				autoExpandParent: true,
			}
		});
	}

	let refArr = [];
	const loop = data => data.map((item) => {
		const index = item.name.indexOf(userInfoModel.searchValue);
		const beforeStr = item.name.substr(0, index);
		const afterStr = item.name.substr(index + userInfoModel.searchValue.length);
		const title = index > -1 ? (
			<span ref={(e) => { (userInfoModel.searchValue !== '') && refArr.push(e) }}>
				{beforeStr}
				<span className={styles.selColor}>{userInfoModel.searchValue}</span>
				{afterStr}
				{item.status == 2 ? '（已禁用）' : ''}
			</span>
		) : <span>{item.name}{item.status == 2 ? '（已禁用）' : ''}</span>;
		if (item.children && item.children.length > 0) {
			return (
				<TreeNode key={String(item.id)} title={title} retName={item.name}>
					{loop(item.children)}
				</TreeNode>
			);
		}
		return <TreeNode
			key={item.id + ''}
			title={title}
			retName={item.name}
			disabled={(item.applicationId == undefined && (item.children == undefined || item.children.length == 0)) ? true : false}
		/>;
	});

	setTimeout(() => {
		//搜索到的隐藏内容跳转到可视区
		if (refArr.length != 0) { ReactDOM.findDOMNode(refArr[0]).scrollIntoView(); }
	}, 300)

	const save = () => {
		validateFields((err, values) => {
			if (!err) {
				dispatch({ type: `${namespace}/save` })
			}
		})
	}

	const closeTreeBox = (id) => {

		remove(checkedKeys, (item) => {
			return String(item) == String(id)
		})

		remove(detail.appList, (item) => {
			return String(item.id) == String(id)
		})

		dispatch({
			type: `${namespace}/store`,
			payload: {
				checkedKeys: cloneDeep(checkedKeys),
				detail: cloneDeep(detail)
			}
		});
	}

	const checkTreeBox = (checkedKeys, e) => {
		let arr = [];
		dataList.forEach((item, index) => {
			if (checkedKeys.indexOf(String(item.id)) != -1) {
				if (item.children == undefined || item.children == null || item.children.length == 0) {
					arr.push(item);
				}
			}
		})
		detail.roleList = arr;
		dispatch({
			type: `${namespace}/store`,
			payload: {
				checkedKeys,
				detail: cloneDeep(detail)
			}
		});
	}

	const checkUserName = (rule, value, callback) => {
		let reg = new RegExp(/^[0-9A-Za-z_]+$/);
		if (value && !reg.test(value)) {
			return callback('用户名仅支持数字，字母，下划线');
		}
		callback();
	}

	const checkPasswordAgain = (rule, value, callback) => {
		if (type == 'add' && value && value != detail.password) {
			callback('两次输入密码不一致');
		} else {
			callback();
		}
	}

	const checkPhone = (rule, value, callback) => {
		let reg = new RegExp(/^1\d{10}$/);
		if (value && !reg.test(value)) {
			callback('请输入正确的手机号')
		} else {
			callback();
		}
	}

	const checkPassword = (rule, value, callback) => {
		let regEmpty = new RegExp(/\s/);
		if (type == 'add' && value && regEmpty.test(value)) {
			return callback('密码不能包含空格');
		}
		callback();
	}

	// 路由视图
	return (
		<div className="public_listMain">

			<div className={cx('functionButton', styles.savaBtn)}>
				<Button type='primary' loading={userInfoModel.saveDisabled} onClick={() => { save() }}><i className={"iconfont icon-baocun"}></i>保存</Button>
			</div>

			<Form>
				{/*解决360自动填充的bug*/}
				<div style={{ position: 'absolute', zIndex: -1, top: -300, visibility: 'hidden' }}><Input type={'text'} /><Input type={'password'} id={'0'} /></div>

				<CollapsiblePanels title={'用户详情'}>
					<div className={cx(styles.infoWrap)}>
						<Row gutter={4}>
							<Col span={8}>
								<FormItem {...formItemLayout} label={<span>用户名</span>} hasFeedback>
									{getFieldDecorator('userName', {
										rules: [{
											required: true, max: 32, message: '请输入用户名,长度不超过32!',
										}, {
											validator: checkUserName
										}],
										initialValue: detail.userName
									})(
										<Input autoComplete={'off'} tabIndex={'1'} disabled={type == 'edit' ? true : false} onChange={(e) => { updateModel(e.target.value, 'userName', 'detail') }} />
									)}
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} label={<span>姓名</span>} hasFeedback>
									{getFieldDecorator('realName', {
										rules: [{
											required: true, max: 20, message: '请输入姓名,长度不超过20!',
										}],
										initialValue: detail.realName
									})(
										<Input autoComplete={'off'} tabIndex={'2'} disabled={(detail.type === 5 || detail.type === 8) ? true : false} onChange={(e) => { updateModel(e.target.value, 'realName', 'detail') }} />
									)}
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} label={<span>手机号码</span>} hasFeedback>
									{getFieldDecorator('phone', {
										rules: [{
											required: false, max: 11, message: '请输入手机号码,长度不超过11!',
										}, {
											validator: checkPhone
										}],
										initialValue: detail.phone
									})(
										<Input autoComplete={'off'} tabIndex={'3'} maxLength={'11'} disabled={(detail.type === 5 || detail.type === 8) ? true : false} onChange={(e) => { updateModel(e.target.value, 'phone', 'detail') }} />
									)}
								</FormItem>
							</Col>
						</Row>
						<Row>
							<Col span={8}>
								<FormItem {...formItemLayout} label={<span>密码</span>} style={{ position: 'relative' }} hasFeedback>
									{getFieldDecorator('password', {
										rules: [{
											required: true, message: '请输入密码,密码长度6-16！',
										}, {
											max: 16, message: '密码长度6-16！'
										}, {
											min: 6, message: '密码长度6-16！'
										}, {
											validator: checkPassword
										}],
										initialValue: detail.password
									})(
										<Input
											autoComplete={'off'}
											tabIndex={'4'}
											id={'0'}
											type={'password'}
											disabled={type == 'edit' ? true : false}
											onPaste={(e) => { e.preventDefault() }}
											onChange={(e) => { updateModel(e.target.value, 'password', 'detail') }}
										/>
									)}
									{
										type == 'edit' ?
											<Popconfirm
												title={'确定要重置此用户密码吗?'}
												okText={'确定'}
												cancelText={'取消'}
												onConfirm={() => { dispatch({ type: `${namespace}/resetPwd` }) }}
											>
												<a style={{ position: 'absolute', right: -54, top: 0, fontSize: 10 }}>重置密码</a>
											</Popconfirm>
											: null
									}
								</FormItem>
							</Col>
							<Col span={8}>
								<FormItem {...formItemLayout} label={<span>重复密码</span>} hasFeedback>
									{getFieldDecorator('confirmPassword', {
										rules: [{
											required: true, max: 20, message: '请输入重复密码,长度6-16!',
										}, {
											validator: checkPasswordAgain
										}],
										initialValue: detail.confirmPassword
									})(
										<Input
											autoComplete={'off'}
											tabIndex={'5'}
											type={'password'}
											disabled={type == 'edit' ? true : false}
											onPaste={(e) => { e.preventDefault() }}
											onChange={(e) => { updateModel(e.target.value, 'confirmPassword', 'detail') }}
										/>
									)}
								</FormItem>
							</Col>
							{
								 <Col span={8}>
									<FormItem {...formItemLayout} label={'所属单位'} hasFeedback>
										{getFieldDecorator('dutyId', {
											rules: [{
												required: false, max: 20, message: '请选择职能',
											}],
											initialValue: detail.dutyId == null ? '' : (detail.dutyId + '')
										})(
											<Select
												disabled={(detail.type === 5 || detail.type === 8) ? true : false}
												onChange={(value) => { updateModel(value, 'dutyId', 'detail') }}>
												<Option value={''}>请选择</Option>
												{
													dutyList.map((e, i) => {
														return <Option key={i} value={e.id + ''}>{e.dutyName}</Option>
													})
												}
											</Select>
										)}
									</FormItem>
								</Col>


							}

                            <Col span={8}>
                                <FormItem {...formItemLayout} label={<span>岗位</span>} hasFeedback>
                                    {getFieldDecorator('realName', {
                                        rules: [{
                                            required: true, max: 20, message: '请输入姓名,长度不超过20!',
                                        }],
                                        initialValue: detail.realName
                                    })(
                                        <Input autoComplete={'off'} tabIndex={'2'} disabled={(detail.type === 5 || detail.type === 8) ? true : false} onChange={(e) => { updateModel(e.target.value, 'realName', 'detail') }} />
                                    )}
                                </FormItem>
                            </Col>
						</Row>
					</div>
				</CollapsiblePanels>

				<CollapsiblePanels title={'用户角色'} style={{ marginTop: 16 }}>
					{
						routeObj.config && routeObj.config.requireOrgMgmt == true ?
							<Row style={{ marginBottom: 16 }}>
								<Col>
									<div className={styles.selfLabel}>
										<label>用户类型：</label>
										<RadioGroup onChange={(e) => { updateModel(e.target.value, 'roleType') }} disabled={type == 'edit' ? true : false} value={roleType}>
											<Radio value={'sys'}>系统管理用户</Radio>
											<Radio value={'org'}>组织管理员</Radio>
										</RadioGroup>
									</div>
								</Col>
							</Row>
							: null
					}
					{
						roleType == 'org' ?
							<Row style={{ height: 446 }}>
								<Col span={10} className={styles.infoWrap}>
									<FormItem {...formItemLayout} label={<span>管理组织</span>} hasFeedback>
										{getFieldDecorator('orgId', {
											rules: [{
												required: true, message: '请选择组织',
											}],
											initialValue: String(detail.orgId)
										})(
											<Select
												placeholder="请选择组织"
												onChange={(value) => { updateModel(value, 'orgId', 'detail') }}>
												{
													organizeList.map((e, i) => {
														return <Option key={i} value={e.id}>{e.orgName}</Option>
													})
												}
											</Select>
										)}
									</FormItem>

								</Col>
								<Col span={8}></Col>
								<Col span={8}></Col>
							</Row>
							: null
					}
					{
						roleType == 'sys' ?
							<Row gutter={16}>
								<Col span={12}>
									<div className={styles.listFont}>待选角色列表</div>
									<div className={styles.list}>
										<div className={styles.search}>
											<Search placeholder={'搜索角色'} onSearch={(e) => { getSearchKey(e) }} />
										</div>
										<div className={styles.roleList}>
											{
												roleTree && roleTree.length != 0 ?
													<Tree
														checkable={true}
														showLine={true}
														defaultExpandAll={true}
														onCheck={(c, e) => { checkTreeBox(c, e) }}
														onExpand={onExpand}
														expandedKeys={userInfoModel.expandedKeys}
														autoExpandParent={userInfoModel.autoExpandParent}
														checkedKeys={checkedKeys}
													>
														{loop(roleTree)}
													</Tree>
													: null
											}
										</div>
									</div>
								</Col>
								<Col span={12}>
									<div className={styles.listFont}>已选的角色：</div>
									<div className={cx(styles.list)} style={{ overflowY: 'scroll', padding: 4 }}>
										{
											detail.roleList && detail.roleList.map((item, index) => {
												return <span key={index} className={styles.spanTab}>
													{item.name}
													{item.status == 2 ? '（已禁用）' : ''}
													{/*<Icon className={styles.iconClose} onClick={() => { closeTreeBox(item.id) }} type="close" />*/}
												</span>
											})
										}
									</div>
								</Col>
							</Row>
							: null
					}

				</CollapsiblePanels>
			</Form>
		</div>
	);
};

export default connect(({ userInfoModel }) => ({ userInfoModel }))(Form.create()(userInfoView));
